﻿@using WishlistUtilities;
@{
	PageData["Title"] = "Create a new User";
    
    WebSecurity.RequireAuthenticatedUser();
    if (!Roles.IsUserInRole("admin")) {
    	Response.Redirect("~");
    }
    
	var username = "";
	var firstName = "";
	var lastName = "";
	var email = "";
	var recoveryAnswer = "";

	var db = Database.Open("wishlistdb");
}

<h1>Account Creation</h1>
Use the form below to create a new account.<br/>
@if (IsPost) {
	username = Request["username"];
	firstName = Request["firstName"];
	lastName = Request["lastName"];
	email = Request["email"];
	var password = Request["password"];
	recoveryAnswer = Request["recoveryAnswer"];
    var errorMessage = "";

    //Validate user input

	if (username.IsEmpty() ||
		firstName.IsEmpty() ||
		lastName.IsEmpty() ||
		email.IsEmpty()) {
		errorMessage += "<li>Username, First Name, Last Name, or E-mail cannot be empty.</li>";
    }
    if (!ValidationUtility.IsValidEmail(email)) {
        errorMessage += "<li>Please enter a valid e-mail.</li>";
    }
    if (password != Request["confirmPassword"] || password.IsEmpty()) {
        errorMessage += "<li>Passwords do not match or are empty!  Please try again.</li>";
    }
    if (!Request["recoveryQuestion"].IsInt()) {
        errorMessage += "<li>You did not provide a recovery question.  This form may have been tampered with!</li>";
    }
    if (recoveryAnswer.IsEmpty()) {
        errorMessage += "<li>Please provide a recovery answer.</li>";
    }

    //If no errors in validation, continue with registration
    if (errorMessage.IsEmpty()) {
        var sluggedUserName = SlugUtility.CreateSlug(username);
        //Replace slug character with SQL wildcard _
        var sqlSluggedUsername = sluggedUserName.Replace(SlugUtility.SLUGREPLACEMENTCHAR, '_');
        //Check to see if there is a username slug that already matches in the database
        var duplicateUser = db.QueryValue("SELECT COUNT(*) FROM WishlistUser WHERE Username LIKE @0", sqlSluggedUsername) > 0;
        if (!duplicateUser) {
            var confirmationToken = "";
            var userId = 0;
            //Try database operations to create user and his or her lists
            try {
                //Insert user information into user table
                db.Execute(@"INSERT INTO WishlistUser (Username, FirstName, LastName, Email, RecoveryQuestionId, RecoveryAnswer)
                    VALUES (@0, @1, @2, @3, @4, @5)",
                    username, firstName, lastName, email, Request["recoveryQuestion"].AsInt(), 
                    Request["recoveryAnswer"].ToLowerInvariant());
                //Create account, requiring confirmation
                confirmationToken = WebSecurity.CreateAccount(username, password);
                //If administrator, give rights by assigning the admin role
                //if (Request["isAdmin"].AsBool()) {
                //    Roles.AddUserToRole(username, "admin");
                //}
                //Create default list for new user and insert it
                var slug = SlugUtility.CreateSlug("My Default List");
                userId = (int)db.GetLastInsertId();
                db.Execute(@"INSERT INTO List (Name, Description, Slug, WishlistUserId) 
                    VALUES (@0, @1, @2, @3)", "My Default List", "My Description", slug, userId);
                var listId = db.GetLastInsertId();
                //Set default list for user
                db.Execute("UPDATE WishlistUser SET DefaultListId = @0 WHERE Id = @1", listId, userId);
                
                 Response.Redirect("~/Admin/UserManagement");
            } catch (Exception ex) {
                Response.Write(ex.ToString());
            }
         } else {
            errorMessage += "<li>Your username already exists in the system.  Please try another username.</li>";
        }
    }
    if (!errorMessage.IsEmpty()) {
        @RenderPage("~/Shared/Errors/_FormInputError.cshtml", errorMessage);
    }
}
@{
    var questionQuery = db.Query("SELECT * FROM RecoveryQuestion");
}
<div>
    <form id="validateForm" method="post" action="">
	    <fieldset>
		    <legend>Create User</legend>
		    @RenderPage("~/Shared/_PrePopInputFormField.cshtml",
                new { labelName = "username", labelDisplay = "Username:", inputValue = username, maxLength = 30, required = true})
            @RenderPage("~/Shared/_PrePopInputFormField.cshtml",
                new { labelName = "firstName", labelDisplay = "First Name:", inputValue = firstName, maxLength = 50, required = true})
		    @RenderPage("~/Shared/_PrePopInputFormField.cshtml",
                new { labelName = "lastName", labelDisplay = "Last Name:", inputValue = lastName, maxLength = 50, required = true})
		    @RenderPage("~/Shared/_PrePopInputFormField.cshtml",
                new { labelName = "email", labelDisplay = "E-mail:", required = true, inputValue = email, validationClasses = "email", maxLength = 50})
		    @RenderPage("~/Shared/_PrePopInputFormField.cshtml",
                new { labelName = "password", labelDisplay = "Password:", inputType = "password", required = true})
		    @RenderPage("~/Shared/_InputFormField.cshtml",
                new { labelName = "confirmPassword", labelDisplay = "Confirm Password:", inputType = "password", required = true, 
                    validationAttributes = "equalTo=\"#password\""})
		    <div class="editor-label">
			    <label for="recoveryQuestion">Choose a password recovery question:</label>
		    </div>
		    <div class="editor-field">
			    <select id="recoveryQuestion" name="recoveryQuestion">
				    @foreach (var question in questionQuery) {
					    <option value="@question.Id">@question.Text</option>
				    }
			    </select>
		    </div>
            @RenderPage("~/Shared/_PrePopInputFormField.cshtml",
                new { labelName = "recoveryAnswer", labelDisplay = "Recovery Answer:", inputValue = recoveryAnswer, maxLength = 100, required = true})
		    <div class="submit-group">
			    <input type="submit" value="Create" onclick="javascript:$('#validateForm').validate()" />
			    <input type="reset" value="Reset" />
		    </div>
	    </fieldset>
    </form>
</div>
